from flask import Flask,render_template,request,make_response,redirect
from flask import g
import hashlib

app = Flask(__name__)

@app.route("/user/index")
@app.route("/user/index/<name>")
def index(name = None):
	print(name, flush = True)
	return render_template("user/index.html", name = name)

@app.route("/user/profile")
def profile():
	# uid = request.args.get("id","")
	# print("uid:", uid, flush = True)
	flag = request.cookies.get("login_user")
	print("hash:", flag, flush = True)
	if not flag:
		return redirect("/user/login")
	
	return render_template("user/profile.html", req = request)

@app.route("/user/login", methods = {"GET", "POST"})
def login():
	print("not valid:",request.method, flush = True)
	if(request.method == "POST"):
		username = request.form["username"]
		password = request.form["password"]
		if(username == "zhangsan" and password == "123"):
			@after_this_request
			def save_user_status(response):
				print("after request save_user_status", flush = True)
				# response = make_response()
				md5 = hashlib.md5()
				md5.update(password.encode("utf-8"))
				print("md5:", md5.hexdigest())
				response.set_cookie("login_user", md5.hexdigest())
				return response
			return redirect("/user/profile")
			
		else:
			return redirect("/user/login")
	else:
		return render_template("user/login.html")

def after_this_request(f):
	print("after_this_request", f, flush = True)
	if not hasattr(g, 'after_request_callbacks'):
		g.after_request_callbacks = []
		g.after_request_callbacks.append(f)
	return f

@app.after_request
def call_after_request_callbacks(response):
	print("after request run", response, flush = True)
	for callback in getattr(g, 'after_request_callbacks', ()):
		response = callback(response)
	return response

if __name__ == "__main__":
	app.run()